package com.zlyx.easy.swagger.scanner;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.zlyx.easy.core.annotations.SpringBean;
import com.zlyx.easy.core.loggers.Logger;
import com.zlyx.easy.core.utils.HttpUtils.HttpClient;
import com.zlyx.easy.core.utils.HostUtils;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.core.utils.StringUtils;
import com.zlyx.easy.swagger.cache.ApiCache;
import com.zlyx.easy.swagger.config.EasySwaggerConfiguration.SwaggerProperties;
import com.zlyx.easy.swagger.remote.ApiManagerService;

/**
 * @description 注册docket
 * @author zhaoguang
 * @date 2019年6月21日
 */
@SpringBean(todo = { "加载并注册docket" })
@EnableScheduling
public class SwaggerScanner extends AbstractSwaggerScanner implements BeanFactoryAware, InitializingBean {

	@Autowired
	private ApiManagerService apiManagerService;

	@Value("${springfox.documentation.swagger.v2.path:/}")
	private String webServer;

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		listableBeanFactory = (DefaultListableBeanFactory) beanFactory;
		List<SwaggerProperties> apiProperties = apiConfiguration.getSwaggerProperties();
		if (apiConfiguration.isEnabled() && !apiProperties.isEmpty()) {
			for (SwaggerProperties api : apiProperties) {
				registerDocket(api.getGroupName(), api);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Scheduled(cron = "${easy.swagger.cron:0 0/30 * * * ?}")
	public void scan() throws Exception {
		List<String> urls = apiConfiguration.getUrls();
		if (ObjectUtils.isNotEmpty(urls)) {
			Logger.debug("即将聚合文档，请等待...");
			for (String url : urls) {
				if (!url.endsWith("/")) {
					url = url + "/";
				}
				if (!HostUtils.isCurrentServcer(url)) {
					Logger.debug("正在聚合文档地址" + url);
					ApiCache.addApis(HttpClient.url(url + "easy-swagger/apis/get").get(Map.class));
				}
			}
			Logger.debug("聚合文档已完成。");
		}
	}

	@Override
	public void doOnRefreshed(ApplicationContext context) throws Exception {
		ApiCache.addApis(apiConfiguration.getHost() + webServer, documentationCache.all().keySet());
		if (ApiCache.getApis().size() > 0 & StringUtils.isNotEmpty(apiConfiguration.getManagerUrl())
				&& !HostUtils.isCurrentServcer(apiConfiguration.getManagerUrl())) {
			Logger.debug("正在注册文档到聚合服务，请等待...");
			apiManagerService.registerApis(ApiCache.getApis());
			Logger.debug("注册文档到聚合服务已完成");
		}

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		scan();
	}

}
